package com.sunflower.common.mybatis.core.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.reflect.GenericTypeUtils;
import com.sunflower.common.mybatis.core.mapper.BaseMapperPlus;
import com.sunflower.common.mybatis.core.service.IService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

/**
 * @author: SunLuQuan
 * @Date: 2024年03月24日 18:09
 * @Description: ServiceImpl
 * TODO
 */
public class ServiceImpl<T, M extends BaseMapperPlus<T, V>, V> implements IService<T> {

    @Autowired
    protected M baseMapper;

    protected final Class<?>[] typeArguments = GenericTypeUtils.resolveTypeArguments(this.getClass(), ServiceImpl.class);
    protected final Class<T> entityClass = this.currentModelClass();
    protected final Class<M> mapperClass = this.currentMapperClass();

    protected Class<M> currentMapperClass() {
        return (Class<M>) this.typeArguments[1];
    }

    protected Class<T> currentModelClass() {
        return (Class<T>) this.typeArguments[0];
    }

    /**
     * 保存前的数据处理
     */
    protected void entityBeforeSave(T entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 修改前的数据处理
     */
    protected void entityBeforeUpdate(T entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public boolean insert(T entity) {
        entityBeforeSave(entity);
        return IService.super.insert(entity);
    }

    @Override
    public boolean updateById(T entity) {
        entityBeforeUpdate(entity);
        return IService.super.updateById(entity);
    }

    @Override
    public boolean insertBatch(Collection<T> entityList, int batchSize) {
        return baseMapper.insertBatch(entityList, batchSize);
    }

    @Override
    public boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
        return baseMapper.insertOrUpdateBatch(entityList, batchSize);
    }

    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        return baseMapper.updateBatchById(entityList, batchSize);
    }

    @Override
    public boolean insertOrUpdate(T entity) {
        return baseMapper.insertOrUpdate(entity);
    }

    @Override
    public BaseMapperPlus<T, V> getBaseMapper() {
        return baseMapper;
    }

    @Override
    public Class<T> getEntityClass() {
        return entityClass;
    }
}
